package com.dh.project.utils;

import com.thoughtworks.xstream.XStream;
import okhttp3.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Mc on 2016/9/18.
 */

public class PayUtil {

    public interface ConstAli {
        String PRIVATEKEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCNiEE1nKyQf/7jlhYc9tXtVr9DyCTBQQ/iKKZSgSACZg4/0GHiMney/JHNL/0UmadCyhc0JB60FwDl5mO7df4nl/7+D0ArVnvyBlW26w7vAxVCRVqAPJ25xSoHgWCM0r/nGFa727N4mfMd1doynfK2jBCbX0zlytlmCec/qzYDJ+LbrmSjmZmbhAKbTPdElPZEKN85PFNNBILmK9L3G+b0L1HjE2XoYd0GSfjgPMba2Fq8EAV/QuOLQVSFq9e9jEXtTqRZdXvGIQRjkXYosQLM3eEYQlhMIl6Waas1Ym4HeOSsPMQ/lMk0CmWghrI4zumMNRtSHoUrUza6y8iEJYylAgMBAAECggEAFwTZLkIMIvheWV+Yux8+Tfq04u5TZAcT8UGRQ4vyy9ETcjePI/33T+oaQJgUflw7QvahbX6Oa9Xt9HZTNDMNohzrgSCz3BiV0hhLqpNye1cyBvRGsuKo+ITjwBK/xEempIxl1un1t6C6VNjqQx9DUYNYVBzc4ebrEth7fvR2tW5yXnmi3zpRi2B/NG0zOXQE6jTakWiPow++X24RA41t0R2pBXNLsfpQYBYZS1HJJlr2QDK2nWLTI5QvNV+yTRzMncFe8vNyOCV/gmGew7HoWg8KUzSO5iRI/IcKA54DGvkESZCdYKqDDM0cHwbnKNa29zZEbWQH3SPxlTHwXnIHxQKBgQDB9R474wE67ZD4uALtVt+4R8K2vbuaRQ5N79rGpnLX8VvHRpgw+/873qjZxdZJWeeiwen6+sRbydf0QH+5lcmnwUjbZn6pPpari2IA/ffanwVUqHortAaPFxcBIWGvAj0zOkKkVDK+GQA5iD9ZLjhYeBK2ZMWqAx/JgUy1BvwsdwKBgQC6zh0JPrSMLO16Brqdt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wPJeoT3Ogf3wIDAQAB";
        String ALI_CALLBACK_URL = "http://59.110.142.228:8080/customer/AliPayResult";
        String PRODUCT_CODE = "QUICK_MSECURITY_PAY";
        String APP_ID = "2017091208692026";
        String SERVER_URL = "https://openapi.alipay.com/gateway.do";
    }

    public interface ConstWecheat {
        String Base_URL = "http://59.110.142.228:8080/customer/";
        String APP_ID = "wxdeff58297fbdbeac";
        //    public static String APP_SECERT = "b068a4f1c5ca181e37420a329a40b1ae";
        String MCH_ID = "1488806632";//商户号
        String PACKAGE_VALUE = "Sign=WXPay";//packageValue
        String API_KEY = "f2703bba7f3b536b25861bcc1d4fe0bc";
        String wxNotifyUrl = Base_URL + "WeiXinPayResultNew";//微信回调接口
        String prepayId = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信获取prepayid
    }


    /**
     * 要求外部订单号必须唯一。
     * Z
     *
     * @return
     */
    public static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }


    public static String getSign(Map<String, String> map) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() != "") {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + ConstWecheat.API_KEY;
//        LogUtil.i("Sign Before MD5:" + result);
        result = MD5.MD5Encode(result).toUpperCase();
//        LogUtil.i("Sign Result:" + result);
        return result;
    }

    public static Object getObjectFromXML(String xml, Class tClass) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream();
        xStreamForResponseData.alias("xml", tClass);
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return xStreamForResponseData.fromXML(xml);
    }

    /**
     * Map集合转换xml文档
     */
    public static String mapToXml(HashMap<String, String> paramMap) {
        String xml = "";
        try {
            XStream xstream = new XStream();
            xml = xstream.toXML(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return xml;
    }

    public static void mapToXML(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext(); ) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXML(hm, sb);
                }
                sb.append("</" + key + ">\n");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXML((HashMap) value, sb);
                    sb.append("</" + key + ">");
                } else {
                    sb.append("<" + key + ">" + value + "</" + key + ">");
                }

            }

        }
    }


    /**
     * 获取微信支付链接
     *
     * @param price 最终支付价格
     */
    public static String getPrepayId(String price, int customerId, String nonceStr, String shopName) {
        String responseStr = null;
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", ConstWecheat.APP_ID); //appid：每个公众号都有一个appid
        paramMap.put("mch_id", ConstWecheat.MCH_ID); //商户号：开通微信支付后分配
        paramMap.put("nonce_str", nonceStr);//随机数
        paramMap.put("body", "家有管家-余额充值"); //商品描述
        paramMap.put("attach", customerId + "-" + shopName); //附加数据
        paramMap.put("out_trade_no", getOutTradeNo() + "");//商户订单号
        paramMap.put("total_fee", price); //金额必须为整数  单位为分
        paramMap.put("spbill_create_ip", "192.168.1.31"); //本机的Ip
        paramMap.put("notify_url", ConstWecheat.wxNotifyUrl); //支付成功后，回调地址
        paramMap.put("trade_type", "APP"); //交易类型
        paramMap.put("sign", PayUtil.getSign(paramMap));//根据微信签名规则，生成签名。随机参数可以在商户后台管理系统中进行设置。
        StringBuffer sb = new StringBuffer("<xml>");//把参数转换成XML数据格式
        PayUtil.mapToXML(paramMap, sb);
        sb.append("</xml>");
        System.out.println("微信提交xml: \n" + sb.toString());

        RequestBody requestBody = RequestBody.create(MediaType.parse("utf-8"), sb.toString());
        Request request = new Request.Builder().addHeader("Content-Type", "text/xml").url(ConstWecheat.prepayId).post(requestBody).build();


        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            Response response = okHttpClient.newCall(request).execute();
            responseStr = response.body().string();
            System.out.println("weixin return： " + responseStr);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return responseStr;

    }


}
